from sqlalchemy import *
from netaddr import IPNetwork, IPAddress

from config import *

def get_network(ip):
    network_addr = 'unknown'
    netadmin_id = -1
   
    
    engine = create_engine(NETADMIN_DB)
    with engine.begin() as connection:
        result = connection.execute('select id,name,address,mask from networks')
        
    for row in result:
        net = row['address'].decode('utf-8')
        mask = str(row['mask'])
        if IPAddress(ip) in IPNetwork(net + "/" + mask):
            netadmin_id = row['id']
            network_addr = row['name'].decode('utf-8')
            break
            
    return {'id' : netadmin_id, 'network' : network_addr}